<template>
  <div class="createPost-container-edit">
    <el-form
      ref="postForm"
      :model="postForm"
      label-position="right"
      class="form-container"
    >
      <div class="createPost-main-container">
        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="项目名称:"
        >
          <el-input
            v-model="postForm.project_name"
            :rows="1"
            type="textarea"
            autosize
            placeholder="请输入项目名称"
          />
        </el-form-item>

        <el-row :gutter="24" type="flex">
          <el-col :span="24">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="项目区域:"
            >
              <v-distpicker
                :province="postForm.province"
                :city="postForm.city"
                :area="postForm.area"
                @selected="onSelected"
              /> </el-form-item></el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="详细地址:"
            >
              <el-input
                v-model="postForm.address"
                :rows="1"
                type="textarea"
                autosize
                placeholder="请输入详细地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="开标时间:"
            >
              <el-date-picker
                v-model="postForm.bid_open_time"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择开标时间"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="资格条件:"
            >
              <el-input
                v-model="postForm.qualifications"
                :rows="1"
                type="textarea"
                autosize
                placeholder="请输入资格条件"
              /> </el-form-item></el-col>
          <el-col :span="13">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="人员要求:"
            >
              <el-input
                v-model="postForm.researchers"
                :rows="1"
                type="textarea"
                autosize
                placeholder="请输入人员要求"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="建设单位:"
            >
              <el-input
                v-model="postForm.construction_unit"
                :rows="1"
                type="textarea"
                autosize
                placeholder="请输入建设单位"
              /> </el-form-item></el-col>
          <el-col :span="13">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="代理单位:"
            >
              <el-input
                v-model="postForm.agent_unit"
                :rows="1"
                type="textarea"
                autosize
                placeholder="请输入代理单位"
              /> </el-form-item></el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="11">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="工程费用:"
            >
              <el-input
                v-model="postForm.engineering_cost"
                :rows="1"
                type="textarea"
                autosize
                placeholder="格式:100.00"
              /> </el-form-item></el-col>
          <el-col :span="13">
            <el-form-item
              style="margin-bottom: 10px"
              label-width="120px"
              label="最高限价:"
            >
              <el-input
                v-model="postForm.price_ceiling"
                :rows="1"
                type="textarea"
                autosize
                placeholder="格式:100.00"
              /> </el-form-item></el-col>
        </el-row>
        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="业务类型:"
        >
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="监理" />
            <el-checkbox label="代理" />
            <el-checkbox label="造价咨询" />
            <el-checkbox label="全过程工程咨询" />
            <el-checkbox label="项目管理" />
            <el-checkbox label="其他" />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="项目概况:"
        >
          <el-input
            v-model="postForm.project_overview"
            :rows="1"
            type="textarea"
            autosize
            placeholder="请输入项目概况"
          />
        </el-form-item>

        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="分值组成:"
        >
          <el-input
            v-model="postForm.scores"
            :rows="1"
            type="textarea"
            autosize
            placeholder="请输入分值组成"
          />
        </el-form-item>

        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="资信分情况:"
        >
          <el-input
            v-model="postForm.credit_points"
            :rows="1"
            type="textarea"
            autosize
            placeholder="请输入资信分情况"
          />
        </el-form-item>

        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="商务标评分情况:"
        >
          <el-input
            v-model="postForm.business_standard"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 10 }"
            placeholder="请输入商务标评分情况"
          />
        </el-form-item>
        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="文件上传:"
        >
          <el-button
            type="default"
            size="small"
            @click="uploadFile"
          ><span>上传文件</span></el-button>
        </el-form-item>
        <el-form-item
          style="margin-bottom: 10px"
          label-width="120px"
          label="文件描述:"
        >
          <viewer
            ref="viewer"
            :images="images"
            class="viewer"
            style="width: 100px; boder: 1px solid red;display:none"
            @inited="inited"
          >
            <img
              v-for="(src, index) in images"
              :key="index"
              :src="src"
              class="image"
            >
          </viewer>
          <div class="container">
            <div
              v-for="(item, index) in file_list"
              :key="index"
              class="box"
              :class="item.active == 1 ? 'active' : ''"
              @click="changeBg(index)"
              @dblclick="dbClick(item.name, index)"
            >
              <div class="iconBox">
                <div class="btnDelete" @click="deleteFile(index)" />

                <img width="80" height="80" :src="item.urls" alt="">
              </div>
              <div class="fileText">
                <span
                  :title="item.name"
                  style="
              white-space: nowrap;
              text-overflow: ellipsis;
              width: 100%;
              overflow: hidden;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              display: -webkit-box;
            "
                >{{ item.name }}</span>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-dialog
          title="上传文件"
          :close-on-click-modal="false"
          :visible.sync="uploadFileDialog"
          width="500px"
        >
          <el-upload
            ref="upload"
            class="upload-input"
            drag
            :action="uploadAction"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-success="getFilePath"
            :on-error="handleError"
            :on-change="handleChangeFile"
            :headers="headers"
            :accept="limit_file_type.toString()"
            :limit="3"
            :auto-upload="false"
          >
            <!-- multiple -->
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击选择文件</em>
            </div>
            <div slot="tip" class="el-upload__tip">
              只能上传<span style="color: red">{{
                limit_file_type.join("/").replace(/\./g, "")
              }}</span>文件，且单个文件不超过50MB
            </div>
          </el-upload>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelUpload">取 消</el-button>
            <!-- <el-button type="primary" @click="confirmUpload">确 定</el-button> -->
            <el-button type="primary" @click="submitUpload">上 传</el-button>
          </span>
        </el-dialog>
      </div>
    </el-form>
    <div class="footer" style="width:100%;text-align:center;padding:10px">
      <el-button
        style="margin-left: 10px;border:1px silid red"
        type="success"
        @click="submitForm"
      >修改</el-button>
      <router-link :to="'/project/index'">
        <el-button
          style="margin-left: 30px"
          size="medium"
          type="default"
        >返回</el-button>
      </router-link>
    </div>
  </div>
</template>

<script>
// import Sticky from '@/components/Sticky' // 粘性header组件
import VDistpicker from 'v-distpicker'
import { updateProject, getProjectDetail } from '@/api/project'
import { getInfo } from '@/api/user'
import { getToken } from '@/utils/auth'

const defaultForm = {
  projectArea: {}, // 项目区域
  address: '', // 详细地址
  projectAreaStr: '', // 选择的地区字符串
  bidOpeningTime: '', // 开标时间
  projectName: '', // 项目名称
  qualifications: '', // 资格条件
  researchers: '', // 人员要求
  constructionUnit: '', // 建设单位
  agentUnit: '', // 代理单位
  projectOverview: '', // 项目概况
  scores: '', // 分值组成
  business_standard: '', // 商务标评分情况
  credit_points: '', // 资信分情况
  price_ceiling: '', // 最高限价
  engineering_cost: '', // 工程费用
  business_type: '', // 业务类型
  file_path: [] // 附件地址
}

export default {
  name: 'ArticleDetail',
  components: {
    // Sticky,
    VDistpicker
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      projectId: '', // 当前项目id
      uploadFileDialog: false,
      images: [], // 图片预览数组
      file_list: [], // 处理过后的需要上传的文件数组
      username: '',
      file_types: {
        docx: ['doc', 'docx'],
        xlsx: ['xls', 'xlsx'],
        ppt: ['ppt', 'pptx'],
        jpg: ['jpg', 'jpeg'],
        zip: ['zip', 'rar'],
        txt: ['txt', 'text'],
        mpge: ['mp3', 'mp4'],
        pdf: ['pdf'],
        png: ['png'],
        folder: ['folder']
      },
      // 添加头部请求
      headers: {
        Authorization: 'Bearer ' + getToken(),

        post: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      },
      uploadAction: 'adminapi/project/insertFile',
      checkList: [] // 业务类型
    }
  },
  computed: {
    // 计算属性的 getter
    limit_file_type: function() {
      const limit_file_type = []
      for (const i in this.file_types) {
        this.file_types[i].forEach(_type => {
          if (_type != 'folder') {
            limit_file_type.push('.' + _type)
          }
        })
      }

      // `this` 指向 vm 实例
      return limit_file_type
    }
  },
  created() {
    const id = this.$route.query.id
    this.projectId = id
    this.getProjectData(id)
    this.getUserInfo()
  },
  methods: {
    // 删除文件
    deleteFile(index) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButton: '取消',
        type: 'warning'
      })
        .then(() => {
          this.file_list.splice(index, 1)
        })
        .catch(() => {})
    },
    // 双击事件
    dbClick(fileName, index) {
      if (
        this.file_list[index].fileType == 'png' ||
        this.file_list[index].fileType == 'jpg' ||
        this.file_list[index].fileType == 'jpeg'
      ) {
        const arr = []
        arr.push(this.file_list[index].url)
        this.images = arr

        this.$viewer.view(0)
      } else {
        this.$message({
          type: 'info',
          message: '当前类型文件不支持预览!'
        })
      }
    },
    // 鼠标选中文件改变背景颜色
    changeBg(index) {
      let num
      for (let i = 0; i < this.file_list.length; i++) {
        if (i === index) {
          num = i
        } else {
          this.file_list[i].active = 0
        }
      }
      this.file_list[num].active = 1
    },
    // 确认上传
    submitUpload() {
      this.$refs.upload.submit()
      this.uploadFileDialog = false
    },
    // 根据返回的数据类型显示不同的图片
    getIconUrl(type) {
      const types_icon_arr = this.file_types
      let show_tyupe = 'none'
      for (const i in types_icon_arr) {
        types_icon_arr[i].forEach(_type => {
          if (type == _type) {
            show_tyupe = i
            // break;
          }
        })
      }

      return require('@/assets/resourse/' + show_tyupe + '.png')
    },
    // 区域选择
    onSelected(data) {
      this.postForm.projectArea.province = data.province.value
      this.postForm.projectArea.city = data.city.value
      this.postForm.projectArea.area = data.area.value
      this.projectAreaStr =
        data.province.value + data.city.value + data.area.value
    },
    inited(viewer) {
      this.$viewer = viewer
    },
    // 上传方法
    uploadFile() {
      this.uploadFileDialog = true
      this.file_new_names = {}
      this.fileLists = []
    },
    // 取消dialog
    cancelUpload() {
      this.uploadFileDialog = false
    },
    // 提交表单
    submitForm() {
      this.postForm.file_path = this.file_list
      this.postForm.business_type = this.checkList
      new Promise((resolve, reject) => {
        updateProject({
          projectList: this.postForm,
          id: this.projectId,
          username: this.username
        }).then(response => {
          if (response.data == '1') {
            this.$router.push('/project/index')
            this.$message({
              type: 'success',
              message: '项目修改成功!'
            })
          }
        })
      })
    },
    // 区域选择
    onSelected(data) {
      this.postForm.province = data.province.value
      this.postForm.city = data.city.value
      this.postForm.area = data.area.value
      this.projectAreaStr =
        data.province.value + data.city.value + data.area.value
    },
    // 获取项目
    getProjectData(id) {
      new Promise((reslove, reject) => {
        getProjectDetail({ id: id }).then(response => {
          // console.log(response.data);
          const business_arr = response.data.business_type.split(',')
          this.checkList = business_arr
          this.postForm = response.data
          const fileList = this.postForm.file_path
          for (let i = 0; i < fileList.length; i++) {
            if (fileList[i].type == '2') {
              if (
                fileList[i].fileType == 'png' ||
                fileList[i].fileType == 'jpeg' ||
                fileList[i].fileType == 'jpg'
              ) {
                this.file_list.push({
                  name: fileList[i].file_name,
                  url: fileList[i].file_path,
                  urls: fileList[i].file_path,
                  fileType: fileList[i].fileType
                })
              } else {
                this.file_list.push({
                  name: fileList[i].file_name,
                  url: fileList[i].file_path,
                  urls: this.getIconUrl(fileList[i].fileType),
                  fileType: fileList[i].fileType
                })
              }
            }
          }
        })
      })
    },
    // 获取文件返回路径 需要先上传 上传成功后返回路径再保存到数据库
    getFilePath(res) {
      if (res.data != null) {
        this.$message({
          type: 'success',
          message: '上传成功!'
        })
        if (
          res.data.fileType == 'png' ||
          res.data.fileType == 'jpeg' ||
          res.data.fileType == 'jpg'
        ) {
          // this.images.push(res.data.file_path);
          this.file_list.push({
            name: res.data.name,
            url: res.data.url,
            urls: res.data.url,
            fileType: res.data.fileType
          })
        } else {
          this.file_list.push({
            name: res.data.name,
            url: res.data.url,
            urls: this.getIconUrl(res.data.fileType),
            fileType: res.data.fileType
          })
        }
      }
    },
    // 上传前文件类型判断
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      let is_overflow = 1

      this.limit_file_type.forEach((item, index) => {
        if (item == '.' + testmsg) {
          is_overflow = 0
        }
      })
      if (is_overflow) {
        this.$message({
          message:
            '上传文件只能是 ' +
            this.limit_file_type.toString().replace(/\./g, '') +
            '格式!',
          type: 'error'
        })
      }
      return !is_overflow
    },
    // 选择文件发生变化钩子
    handleChangeFile() {
      this.fileLists = this.$refs.upload.$children[0].fileList
    },
    // 文件限制
    handleExceed(files, fileList) {
      this.$message.warning(`一次最多只可上传3个文件`)
    },
    // 文件移除前
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 上传失败
    handleError(err, file, fileList) {
      this.$message({
        type: 'error',
        message: '上传失败,请重新上传!'
      })
    },
    // 文件移除
    handleRemove(file, fileList) {
      // console.log(this.submitFrom.file_path);
      // 删除暂存在需要保存到数据库数组中的数据
      for (let i = 0; i < this.postForm.file_path.length; i++) {
        if (this.postForm.file_path[i].name == file.name) {
          this.postForm.file_path.splice(i, 1)
          return
        }
      }
    },
    // 获取当前用户的登录信息
    getUserInfo() {
      new Promise((resolve, reject) => {
        getInfo().then(response => {
          this.username = response.data.name // 当前登录用户的姓名
          this.user_id = response.data.id
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-form-item {
  margin: 0px;
}
</style>
<style lang="scss">
@import "~@/styles/mixin.scss";

.createPost-container-edit {
  position: relative;
  .el-date-editor {
    .el-input__inner {
      height: 33px;
    }
  }
  .createPost-main-container {
    padding: 40px 45px 0px 50px;
    .el-form-item {
      .el-form-item__content {
        .distpicker-address-wrapper select {
          width: auto;
          height: 33px;
          padding: 5px 15px;
        }
      }
    }
    .container {
      /* width: 100%; */
      // margin: 10px;
      /* border: 1px solid red; */
      display: grid;
      grid-row-gap: 20px;
      grid-column-gap: 20px;
      grid-template-columns: repeat(auto-fill, 100px);
      .box {
        width: 112px;
        height: 136px;
        // margin: 5px;
        padding: 10%;
        .iconBox {
          width: 100%;
          height: 80px;
          text-align: center;
          position: relative;
          .btnDelete {
            width: 14px;
            height: 14px;
            background: rgb(146, 145, 145);
            border: 0px none;
            /* border-radius: 1px; */
            position: absolute;
            float: right;
            text-align: center;
            line-height: 14px;
            top: 0px;
            right: 0px;
            display: block;
          }
          .btnDelete::after {
            content: "X";
            font-size: 16px;
            color: #fff;
          }
        }
      }
      .fileText {
        width: 100%;
        margin-top: 10px;
        text-align: center;
        height: 23px;
        line-height: 23px;
        color: #595c5f;
        font-size: 15px;
      }
    }
    .postInfo-container {
      position: relative;
      @include clearfix;
      text-align: center;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
  .el-textarea__inner {
    background-color: white;
    color: #000;
    opacity: 0.7;
  }
}
</style>
